package com.xhqgov.manage.controller;

import com.dingtalk.api.response.OapiSsoGettokenResponse;
import com.dingtalk.api.response.OapiSsoGetuserinfoResponse;
import com.xhqgov.manage.model.User;
import com.xhqgov.manage.util.CONST;
import com.xhqgov.manage.util.DDUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Map;

@Controller
public class LoginController extends BaseController{
    private static final Logger LOGGER = Logger.getLogger(LoginController.class);
    @Resource
    private DDUtil ddUtil;

    /**
     * 后台点击E应用进入的方法
     * @param map
     * @param code
     * @return
     */
    @RequestMapping("getCode")
    public String getCode(Map<String,Object> map,String code){
        map.put("code",code);
        return "login";
    }

    /**
     * 将钉钉传来的CODE做校验
     * @param code
     * @return
     */
    @RequestMapping("login")
    @ResponseBody
    public Map<String,Object> login(String code){
        if(StringUtils.isEmpty(code)){
            return clientMap().failure().message("请使用钉钉管理后台登录！").map();
        }
        OapiSsoGettokenResponse response = ddUtil.gettokenResponse();
        if(null == response||StringUtils.isEmpty(response.getAccessToken())){
            return clientMap().failure().message("请求钉钉服务器token失败！").map();
        }
        OapiSsoGetuserinfoResponse responseUserInfo = ddUtil.validateAdmin(code,response.getAccessToken());
        if(null == responseUserInfo||!responseUserInfo.getIsSys()){
            return clientMap().failure().message("您不是管理员不能登录！").map();
        }
        User user = new User();
        BeanUtils.copyProperties(responseUserInfo.getUserInfo(),user);
        setSessionObject(CONST.SESSION_KEY, user);
        return clientMap().success().message("登录成功！").map();
    }
    /**
     * 没有登录的被拦截的界面
     * @return
     */
    @RequestMapping("/nologin")
    public String nologin(){
        return "nologin";
    }

    @RequestMapping("/test")
    public void test(){

    }
}
